package com.ff.neuropp.util;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 融云平台相关
 */
@Component
@Slf4j
public class RyUtils {

    private static final String nonce = "neuropp";

    private static final int TIME_OUT = 60000;

//    @Value("${rongcloud.url}")
//    private String ry_url;
//
//    @Value("${rongcloud.appkey}")
//    private String appKey;
//
//    @Value("${rongcloud.appsecret}")
//    private String appSecret;

    //	api-cn.ronghub.com
    //  api2-cn.ronghub.com
    //  api-sg01.ronghub.com
    private static final String ry_url="https://api-cn.ronghub.com/user/getToken.json";

    private static final String appKey="pwe86ga5p9kf6";

    private static final String appSecret="5jr59ufjX9FZOn";

    /**
     * 获取token
     * @param userid
     * @param name
     * @param headImg
     * @return
     */
    public  String getToken(String userid,String name,String headImg){
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userId",userid));
        params.add(new BasicNameValuePair("name",name));
        params.add(new BasicNameValuePair("portraitUri",headImg));
        String result = postWithParamsForString(params);
        if(StringUtils.isNotBlank(result)){
             Map<String,Object> map  = JSONObject.parseObject(result);
             return (String)map.get("token");
        }
        return null;
    }


    private  String postWithParamsForString(List<NameValuePair> params){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(ry_url);
        String time = String.valueOf(new Date().getTime());
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("App-Key",appKey);
            httpPost.setHeader("Nonce",nonce);
            httpPost.setHeader("Timestamp",time);
            httpPost.setHeader("Signature",sha1(time));
            httpPost.setConfig(RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build());
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                String msg = EntityUtils.toString(entity);
                return msg;
            }
        } catch (IOException e) {
            log.error("get rongcloud token error, {}",e);
            return null;
        }
        return null;
    }


    private String sha1(String time){
        return DigestUtils.sha1Hex(appSecret+nonce+time);
    }

    public static void main(String[] args) {
        RyUtils ry = new RyUtils();
        System.out.println(ry.getToken("1","a","xx"));
    }
}
